package com.pai4j.user.controller;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.domain.vo.request.group.*;
import com.pai4j.domain.vo.response.group.GroupInfoResponseVO;
import com.pai4j.domain.vo.response.group.GroupMemberResponseVO;
import com.pai4j.domain.vo.response.group.GroupInvitationResponseVO;
import com.pai4j.domain.vo.response.group.JoinGroupResponseVO;
import com.pai4j.remote.user.GroupClient;
import com.pai4j.user.service.group.GroupService;
import com.pai4j.user.service.group.GroupMemberService;
import com.pai4j.user.service.group.GroupInvitationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GroupController implements GroupClient {

    @Autowired
    private GroupService groupService;
    
    @Autowired
    private GroupMemberService groupMemberService;
    
    @Autowired
    private GroupInvitationService groupInvitationService;
    
    @Autowired
    private com.pai4j.user.service.group.GroupJoinApplicationService groupJoinApplicationService;
    /**
     * 创建或更新群组信息
     *
     * @param request 包含群组创建或更新信息的请求对象
     * @return 返回包含群组信息的响应对象
     */
    @Override
    public PAIResponseBean<GroupInfoResponseVO> createOrUpdate(@RequestBody CreateOrUpdateGroupRequestVO request) {
        return PAIResponseBeanUtil.success(groupService.createOrUpdate(request));
    }

    /**
     * 根据群组ID获取群组信息
     *
     * @param paiId 群组的唯一标识符
     * @return 返回包含群组信息的响应对象
     */
    @Override
    public PAIResponseBean<GroupInfoResponseVO> get(@PathVariable String paiId) {
        return PAIResponseBeanUtil.success(groupService.get(paiId));
    }

    /**
     * 更新群组成员设置
     *
     * @param request 包含成员设置更新信息的请求对象
     * @return 返回更新操作是否成功的响应对象
     */
    @Override
    public PAIResponseBean<Boolean> updateMemberSetting(@RequestBody UpdateGroupMemberSettingRequestVO request) {
        return PAIResponseBeanUtil.success(groupService.updateMemberSetting(request));
    }

    /**
     * 获取群组成员设置信息
     *
     * @param groupPaiId 群组的唯一标识符
     * @param userAccount 用户账号
     * @return 返回包含成员设置信息的响应对象
     */
    @Override
    public PAIResponseBean<UpdateGroupMemberSettingRequestVO> getMemberSetting(@PathVariable String groupPaiId,
                                                                               @PathVariable String userAccount) {
        return PAIResponseBeanUtil.success(groupService.getMemberSetting(groupPaiId, userAccount));
    }

    // ========== 群成员管理接口实现 ==========
    
    /**
     * 加入群聊（统一入口）
     * 智能处理加群流程，根据群设置自动决定是直接加入还是创建审批申请
     * 
     * @param request 加群请求参数
     * @return JoinGroupResponseVO 加群结果
     *         status=1: 成功加入（群设置为"自由加入"）
     *         status=2: 已提交审批申请（群设置为"需要审批"，系统自动创建申请）
     *         status=3: 群已满
     *         status=4: 已在群内
     *         status=5: 群禁止加入
     */
    @Override
    public PAIResponseBean<JoinGroupResponseVO> joinGroup(@RequestBody JoinGroupRequestVO request) {
        return PAIResponseBeanUtil.success(groupMemberService.joinGroup(request));
    }

    /**
     * 退出群聊
     */
    @Override
    public PAIResponseBean<Boolean> leaveGroup(@RequestBody LeaveGroupRequestVO request) {
        return PAIResponseBeanUtil.success(groupMemberService.leaveGroup(request));
    }

    /**
     * 踢出群成员
     */
    @Override
    public PAIResponseBean<Boolean> kickMembers(@RequestBody KickMemberRequestVO request) {
        return PAIResponseBeanUtil.success(groupMemberService.kickMembers(request));
    }

    /**
     * 管理群成员（任命/撤销管理员、禁言/解禁、转让群主）
     */
    @Override
    public PAIResponseBean<Boolean> manageGroupMember(@RequestBody ManageGroupMemberRequestVO request) {
        return PAIResponseBeanUtil.success(groupMemberService.manageGroupMember(request));
    }

    /**
     * 获取群成员列表
     */
    @Override
    public PAIResponseBean<List<GroupMemberResponseVO>> getGroupMembers(@PathVariable String groupPaiId) {
        return PAIResponseBeanUtil.success(groupMemberService.getGroupMembers(groupPaiId));
    }

    /**
     * 获取群聊当前人数
     */
    @Override
    public PAIResponseBean<Long> getGroupMemberCount(@PathVariable String groupPaiId) {
        return PAIResponseBeanUtil.success(groupMemberService.getGroupMemberCount(groupPaiId));
    }

    /**
     * 获取用户加入的群聊列表
     */
    @Override
    public PAIResponseBean<List<GroupMemberResponseVO>> getUserGroups(@PathVariable String userAccount) {
        return PAIResponseBeanUtil.success(groupMemberService.getUserGroups(userAccount));
    }

    /**
     * 检查用户在群内的权限
     */
    @Override
    public PAIResponseBean<Boolean> hasPermission(@PathVariable String groupPaiId,
                                                 @PathVariable String userAccount,
                                                 @PathVariable String permission) {
        return PAIResponseBeanUtil.success(groupMemberService.hasPermission(groupPaiId, userAccount, permission));
    }

    // ========== 群聊邀请接口实现 ==========
    
    /**
     * 邀请用户加入群聊
     */
    @Override
    public PAIResponseBean<List<String>> inviteToGroup(@RequestBody InviteToGroupRequestVO request) {
        return PAIResponseBeanUtil.success(groupInvitationService.inviteToGroup(request));
    }

    /**
     * 处理群聊邀请（接受/拒绝）
     */
    @Override
    public PAIResponseBean<Boolean> handleInvitation(@RequestBody HandleInvitationRequestVO request) {
        return PAIResponseBeanUtil.success(groupInvitationService.handleInvitation(request));
    }

    /**
     * 获取用户的待处理邀请列表
     */
    @Override
    public PAIResponseBean<List<GroupInvitationResponseVO>> getPendingInvitations(@PathVariable String userAccount) {
        return PAIResponseBeanUtil.success(groupInvitationService.getPendingInvitations(userAccount));
    }

    /**
     * 获取群聊的邀请记录（分页）
     */
    @Override
    public PAIResponseBean<Page<GroupInvitationResponseVO>> getGroupInvitations(@PathVariable String groupPaiId,
                                                                               @RequestParam(defaultValue = "0") int page,
                                                                               @RequestParam(defaultValue = "20") int size) {
        return PAIResponseBeanUtil.success(groupInvitationService.getGroupInvitations(groupPaiId, page, size));
    }

    // ========== 加群审批接口实现 ==========
    
    /**
     * 通过加群申请（强一致性）
     * 参考好友申请的confirmSubscribe设计，提供统一的审批通过接口
     * 备注为可选参数，如果提供备注则发送互动消息通知申请人
     */
    @Override
    public PAIResponseBean<Boolean> approveJoinApplication(@RequestParam("applicationId") Long applicationId, 
                                                            @RequestParam("approverAccount") String approverAccount,
                                                            @RequestParam(value = "approvalRemark", required = false) String approvalRemark) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.approveJoinApplication(applicationId, approverAccount, approvalRemark));
    }
    
    /**
     * 拒绝加群申请（强一致性）
     * 参考好友申请的rejectSubscribe设计，提供统一的审批拒绝接口
     * 拒绝理由为可选参数，如果提供理由则发送互动消息通知申请人
     */
    @Override
    public PAIResponseBean<Boolean> rejectJoinApplication(@RequestParam("applicationId") Long applicationId, 
                                                           @RequestParam("approverAccount") String approverAccount,
                                                           @RequestParam(value = "approvalRemark", required = false) String approvalRemark) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.rejectJoinApplication(applicationId, approverAccount, approvalRemark));
    }
    
    /**
     * 处理加群申请（群主/管理员审批）
     * @deprecated 建议使用 approveJoinApplication 或 rejectJoinApplication 方法
     *   该方法已弃用，请使用 approveJoinApplication 或 rejectJoinApplication 方法
     * 注意：用户加群请使用 joinGroup 方法，系统会根据群设置自动处理
     * （直接加入或自动创建审批申请），无需手动调用申请接口
     */
    @Deprecated
    @Override
    public PAIResponseBean<Boolean> handleJoinApplication(@RequestBody HandleJoinApplicationRequestVO request) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.handleJoinApplication(request));
    }

    /**
     * 获取群组的待审批申请列表（分页）
     * 仅群主和管理员可查看
     */
    @Override
    public PAIResponseBean<Page<com.pai4j.domain.vo.response.group.GroupJoinApplicationResponseVO>> getGroupPendingApplications(
            @PathVariable String groupPaiId,
            @RequestParam("requesterAccount") String requesterAccount,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.getGroupPendingApplications(groupPaiId, requesterAccount, pageNum, pageSize));
    }

    /**
     * 获取群组的待审批申请数量
     * 仅群主和管理员可查看
     */
    @Override
    public PAIResponseBean<Long> getGroupPendingApplicationCount(
            @PathVariable String groupPaiId,
            @RequestParam("requesterAccount") String requesterAccount) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.getGroupPendingApplicationCount(groupPaiId, requesterAccount));
    }

    /**
     * 获取用户的申请历史（分页）
     */
    @Override
    public PAIResponseBean<Page<com.pai4j.domain.vo.response.group.GroupJoinApplicationResponseVO>> getUserApplicationHistory(
            @PathVariable String applicantAccount,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.getUserApplicationHistory(applicantAccount, pageNum, pageSize));
    }

    /**
     * 检查用户是否有待处理的申请
     */
    @Override
    public PAIResponseBean<Boolean> hasUserPendingApplication(@PathVariable String groupPaiId,
                                                              @PathVariable String applicantAccount) {
        return PAIResponseBeanUtil.success(groupJoinApplicationService.hasUserPendingApplication(groupPaiId, applicantAccount));
    }
}
